/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.shockwave.pdfium.demo.slice;

import com.shockwave.pdfium.PdfDocument;
import com.shockwave.pdfium.PdfiumCore;
import com.shockwave.pdfium.demo.ResourceTable;
import com.shockwave.pdfium.demo.util.GetFile;
import com.shockwave.pdfium.util.LogUtil;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.app.Context;
import ohos.global.resource.RawFileEntry;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Size;

import java.io.File;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * LoadAllPages extends AbilitySlice
 */
public class LoadAllPages extends AbilitySlice {
    private static final String TAG = LoadAllPages.class.getName();
    private static final String FILE_PATH = "entry/resources/rawfile/sample.pdf";
    private static final String FILE_NAME = "sample.pdf";
    private static final int PAGE_NUM = 0;
    Image iv;
    PdfDocument pdfDocument;
    PdfiumCore pdfiumCore;
    int width;
    int height;
    int pageCount;
    int count = 0;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_multiplepages);
        try {
            openPdf(getContext());
        } catch (IOException ex) {
            LogUtil.error(TAG, ex.getMessage());
        }
    }

    private void openPage(FileDescriptor fd) throws IOException {
        try {
            pdfDocument = pdfiumCore.newDocument(fd);
            pageCount = pdfiumCore.getPageCount(pdfDocument);
            pdfiumCore.openPage(pdfDocument, PAGE_NUM,  pageCount - 1);
            width = pdfiumCore.getPageWidthPoint(pdfDocument, PAGE_NUM);
            height = pdfiumCore.getPageHeightPoint(pdfDocument, PAGE_NUM);
            pdfiumCore.closeDocument(pdfDocument);
        }   catch(IOException ex) {
            LogUtil.error(TAG, ex.getMessage());
        }
    }

    void setImage(PdfiumCore pdfiumCore, PdfDocument pdfDocument, int page) {
        Component ivComp = findComponentById(ResourceTable.Id_myimg);
        if (ivComp instanceof  Image) {
            iv = (Image) ivComp;
        }
        if (iv != null) {
            PixelMap.InitializationOptions initializationOptions = new PixelMap.InitializationOptions();
            initializationOptions.pixelFormat = PixelFormat.RGB_565;
            initializationOptions.size = new Size(1000, 1500);
            PixelMap pixelMap = PixelMap.create(initializationOptions);
            pdfiumCore.renderPageBitmap(pdfDocument, pixelMap, page, 0, 0, 1000, 1500);
            iv.setPixelMap(pixelMap);
        }
    }

    private void openPdf(Context ctx) throws IOException {
        RawFileEntry rawFileEntry = getResourceManager().getRawFileEntry(FILE_PATH);
        File file = GetFile.getFileFromRawFile(FILE_NAME, rawFileEntry, getCacheDir());
        FileDescriptor fd = new RandomAccessFile(file, "r").getFD();
        pdfiumCore = new PdfiumCore(ctx);
        pdfDocument = pdfiumCore.newDocument(fd);
        pageCount = pdfiumCore.getPageCount(pdfDocument);
        pdfiumCore.openPage(pdfDocument, PAGE_NUM,  pageCount - 1);
        setImage(pdfiumCore, pdfDocument, PAGE_NUM);

        Component prevComp = findComponentById(ResourceTable.Id_prev);
        if (prevComp instanceof Button) {
            Button prev = (Button) prevComp;
            prev.setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component component) {
                    if (count == -1) {
                        count = pageCount - 1;
                    }
                    setImage(pdfiumCore, pdfDocument, count--);
                }
            });
        }

        Component nextComp = findComponentById(ResourceTable.Id_next);
        if (nextComp instanceof Button) {
            Button next = (Button) nextComp;
            next.setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component component) {
                    if (count == pageCount - 1) {
                        count = 0;
                    }
                    setImage(pdfiumCore, pdfDocument, ++count);
                }
            });
        }
    }
}
